package com.jacob.androidframe.controls;

import com.jacob.androidframe.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ImageViewAutoStretchContent extends ImageView
{
	public static final int		MEASUREMENT_WIDTH				= 0;
	public static final int		MEASUREMENT_HEIGHT				= 1;

	private static final int	DEFAULT_DOMINANT_MEASUREMENT	= MEASUREMENT_WIDTH;

	private int					mDominantMeasurement;

	public ImageViewAutoStretchContent(Context pContext)
	{
		super(pContext);
	}

	public ImageViewAutoStretchContent(Context pContext, AttributeSet attrs)
	{
		this(pContext, attrs, 0);
	}

	public ImageViewAutoStretchContent(Context pContext, AttributeSet attrs, int defStyle)
	{
		super(pContext, attrs, defStyle);
	
		TypedArray _TypedArray = pContext.obtainStyledAttributes(attrs, R.styleable.ImageViewAutoStretchContent);
		mDominantMeasurement = _TypedArray.getInt(R.styleable.ImageViewAutoStretchContent_dominantMeasurement, DEFAULT_DOMINANT_MEASUREMENT);
		_TypedArray.recycle();
	}

	@Override
	protected void onMeasure(int pWidthMeasureSpec, int pHeightMeasureSpec)
	{
		Drawable _Drawable = getDrawable();
		if (_Drawable == null) {
			super.onMeasure(pWidthMeasureSpec, pHeightMeasureSpec);
			return;
		}

		int _DrawableWidth = _Drawable.getIntrinsicWidth();
		int _DrawableHeight = _Drawable.getIntrinsicHeight();
		if (_DrawableWidth <= 0 || _DrawableHeight <= 0) {
			super.onMeasure(pWidthMeasureSpec, pHeightMeasureSpec);
			return;
		}

		int _NewWidth = MeasureSpec.getSize(pWidthMeasureSpec);
		int _NewHeight = MeasureSpec.getSize(pHeightMeasureSpec);

		switch (mDominantMeasurement) {
		case MEASUREMENT_WIDTH:
			_NewHeight = _NewWidth * _DrawableHeight / _DrawableWidth;
			
			break;
		case MEASUREMENT_HEIGHT:
			_NewWidth = _NewHeight * _DrawableWidth / _DrawableHeight;
			break;
		default:
			throw new IllegalStateException("Unknown measurement with ID " + mDominantMeasurement);
		}

		setMeasuredDimension(_NewWidth, _NewHeight);
	}
}
